package MemberService

import (
	"database/sql"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/grand"
	"time"
)

func ReSetPwd(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
	memberModel := (*entity.Member)(nil)
	err := memberDb.Where(g.Map{
		"id": req.Id,
	}).Struct(&memberModel)
	if err != nil && err != sql.ErrNoRows {
		// 有错误，并且不是数据为空的错误，则返回
		return response.FailByRequestMessage(nil, err.Error())
	}
	if memberModel == nil {
		return response.FailByRequestMessage(nil, "账号不存在")
	}
	passwordSalt := grand.Letters(10)
	defaultPassword := "123456"
	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member").Where("id",
		req.Id,
	).Update(g.Map{
		"password":      tools.EncryptPassword(defaultPassword, passwordSalt),
		"password_salt": passwordSalt,
		"update_at":     time.Now().Unix(),
	})
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err := res.RowsAffected()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if row > 0 {
		return response.SuccessByRequestMessage(nil, "成功")
	} else {
		return response.FailByRequestMessage(nil, "失败")
	}
}
